import json
import os
import sys

import django
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
from asgiref.sync import async_to_sync
from utils import models

class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        group = self.scope['url_route']['kwargs'].get("group")
        devtype = self.scope['url_route']['kwargs'].get("type")
        userid = self.scope['url_route']['kwargs'].get("userid")
        print("websocket已连接",message,"编号：",group,devtype,userid)
        connectDispatchDev(devtype,group,userid)
        self.accept('protocol1') # 允许创建连接 需要指定协议
        # self.close()
        # 加入房间
        async_to_sync(self.channel_layer.group_add)(group, self.channel_name)  # 加群
        if(devtype=='dev'):
            async_to_sync(self.channel_layer.group_send)(group, {"type": 'send.group.message', "message":  {'type': 'websocket.receive', 'text': '手机已连接'}})


    def websocket_disconnect(self, message):
        group = self.scope['url_route']['kwargs'].get("group")
        devtype = self.scope['url_route']['kwargs'].get("type")
        print("断开连接",group,devtype)
        # 若断开连接的是小车
        disConnectDispatchDev(devtype,group,self,message)
        async_to_sync(self.channel_layer.group_discard)(group, self.channel_name)
        raise StopConsumer()

    def websocket_receive(self, message):
        # self.send("服务器已接受信息")
        group = self.scope['url_route']['kwargs'].get("group")
        print("服务器收到信息",message,group)
        if message and message["text"].startswith('car:'):
            carData = json.loads(message["text"][4:])
            models.carStatusUpdate(carData)
        async_to_sync(self.channel_layer.group_send)(group, {"type": 'send.group.message', "message": message})

    def send_group_message(self, event):
        text = event["message"]["text"]
        self.send(text)

def connectDispatchDev(type,sid,userid):
    if type == 'dev':
        print("手机连接啦")
        """连接设备为手机"""
        models.existCarObject(sid,userid)
        return
    else:
        """连接设备为小车"""
        print("小车连接啦")
        models.bootCarObject(sid)

def disConnectDispatchDev(type,sid,self,message):
    if type == 'dev':
        print("手机断开啦")
        """连接设备为手机"""
        models.devExit(sid)
        return
    else:
        """连接设备为小车"""
        message["text"] = "小车已经离线"
        print("小车断开啦")
        models.existCarObject(sid)
        async_to_sync(self.channel_layer.group_send)(sid, {"type": 'send.group.message', "message":message })




